package cn.ustb.controller;

import cn.ustb.config.AlipayConfig;
import cn.ustb.service.LevelExamListService;
import cn.ustb.serviceImpl.LevelExamListServiceImpl;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

/**
 * @author ljy
 */
@WebServlet(name = "OrderpayServlet", value = "/pay")
public class OrderpayServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        String courseId=req.getParameter("courseId");
        System.out.println(courseId);
        LevelExamListService levelExamListService=new LevelExamListServiceImpl();
        levelExamListService.updatePayStatus(1,courseId);
        Random random=new Random();
        String dingdannumber = String.valueOf(1000+random.nextInt(9000));
        String price = req.getParameter("dingdanjine");
        String username = req.getParameter("user");
        String address = "114514";
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        try {
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + dingdannumber + "\"," + "\"total_amount\":\""
                    + price + "\"," + "\"subject\":\"" + username + "\"," + "\"body\":\"" + address + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            // 请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            req.setAttribute("result", result);
            System.out.println("result is " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            req.getRequestDispatcher("/alipay.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        doGet(req, resp);
    }
}
